package com.seo4j.adb4j.device;

import com.android.ddmlib.AdbCommandRejectedException;
import com.android.ddmlib.MultiLineReceiver;
import com.android.ddmlib.ShellCommandUnresponsiveException;
import com.android.ddmlib.TimeoutException;
import com.seo4j.adb4j.device.listener.IMemoryUsageListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;


public class MemoryUsageThread implements Runnable {

    private AdbShellDevice device;
    private IMemoryUsageListener listener;
    private boolean stop = false;
    private static final Logger LOG = LoggerFactory.getLogger(MemoryUsageThread.class.getName());

    public MemoryUsageThread(AdbShellDevice device, IMemoryUsageListener listener) {
        this.device = device;
        this.listener = listener;
    }

    @Override
    public void run() {

        if (listener.getPackageName() == null || listener.getPackageName().isEmpty()) {
            return;
        }

        while (!stop) {
            final String pack = listener != null ? listener.getPackageName() : "";
            final String cmd = "dumpsys meminfo ";
            try {
                device.getMonkeyDevice().executeShellCommand(cmd, new MultiLineReceiver() {
                    @Override
                    public boolean isCancelled() {
                        return false;
                    }

                    @Override
                    public void processNewLines(String[] arg0) {
                        for (String line : arg0) {
                            if (line.contains(pack)) {
                                String val = line.substring(0, line.indexOf("kB"));
                                listener.memoryUsage(Integer.parseInt(val.trim()), System.currentTimeMillis());
                            }
                        }

                    }
                });
            } catch (TimeoutException e) {
                LOG.error("",e);
            } catch (AdbCommandRejectedException e) {
                LOG.error("",e);
                stop();
            } catch (ShellCommandUnresponsiveException e) {
                LOG.error("",e);
            } catch (IOException e) {
                LOG.error("",e);
            }
            try {
                Thread.sleep(1200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void stop() {
        stop = true;
    }
}
